package app

import (
	"bytes"
	"compress/gzip"
	"fmt"
	"net/http"
	schemaCustomer "sieve_admin_server_userpass/app/schema/customer"
	"sieve_admin_server_userpass/app/server"
	"strconv"
	"strings"

	"sieve_admin_server_userpass/lib/encoding/json"
	"sieve_admin_server_userpass/lib/log"
	"sieve_admin_server_userpass/lib/util/convert"
	"sieve_admin_server_userpass/lib/util/errors"
)

func HandleExclude(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Access-Control-Allow-Origin", "*")

	ss := strings.Split(r.URL.Path[1:], "/")

	// AppInjector.Router.UserAuthAPI.GetUserUid

	uid := server.GetLoginUid(r)
	if uid == 0 {
		w.WriteHeader(http.StatusForbidden)
		w.Write([]byte("not login"))
		return
	}

	// uid = 240
	// if uid == 0 {
	//	uid = AppInjector.Router.UserAuthAPI.GetUserUid(r)
	// }

	_ = r.ParseForm()
	c := &server.Context{Uid: uid, Args: r.PostForm, Http: &server.ContextHttp{ResponseWriter: w, Request: r}}
	op := ""
	menuAPI := AppInjector.Router.MenuAPI
	userAuthAPI := AppInjector.Router.UserAuthAPI
	UserAPI := AppInjector.Router.UserAPI
	if len(ss) > 1 {
		op = ss[len(ss)-1]
	}
	var data []byte
	var err error
	switch op {
	case "GetUserLoginState":
		{
			// _ = r.ParseForm()
			uid = convert.Atoi(r.PostForm.Get("uid"))
			b := ""
			// b := server.GetSessionKey(uid, false)
			if b == "" {
				b = userAuthAPI.GetUserLoginState(uint64(uid))
			}
			if b != "" {
				b = "null"
			}
			data = []byte(b)
		}
	case "getResource":
		{
			modTree := server.GetModTree(uid)
			data, err = json.Marshal(modTree)
		}
	case "GetSysDefine":
		{
			fmt.Println(c)
			// data, err = exclude.GetSysDefine(c, uid)

			// d := server.GetModTree(uid)
			// d := menuAPI.GetMenus(c).([]*server.BatchModTree)
			var (
				respData = make(map[string]interface{})
			)
			menuMap := menuAPI.API_queryMenuDetail_list(c)
			if menuMap != nil {
				respData = menuMap.(map[string]interface{})
			}

			c.Args.Set("id", strconv.Itoa(uid))
			c.Args.Set("self", strconv.Itoa(1))
			respUser := UserAPI.API_query_list(c)
			if err, ok := respUser.(error); ok && err != nil {
				log.Err(fmt.Sprintf("获取用户信息失败：%+v", err))
			} else {
				for _, v := range respUser.(map[string]interface{})["list"].([]interface{}) {
					respData["UserInfo"] = v.(*schemaCustomer.UserQueryRsp)
					break
				}
			}

			data, err = json.Marshal(respData)
			break
		}
	default:
		{
			err = errors.New("permission denied")
		}
	}
	if err != nil {
		w.WriteHeader(http.StatusForbidden)
		_, _ = w.Write([]byte(err.Error()))
		return
	}
	w.Header().Set("Content-Type", "text/plain; charset=utf-8")
	w.Header().Set("Content-Encoding", "gzip")
	buf := new(bytes.Buffer)
	gzw := gzip.NewWriter(buf)
	leng, err := gzw.Write(data)
	if err != nil || leng == 0 {
		return
	}
	err = gzw.Flush()
	if err != nil {
		return
	}
	err = gzw.Close()
	if err != nil {
		return
	}
	bt := buf.Bytes()
	_, _ = w.Write(bt)
}
